export let dateFormat = (timeStr) => {
    var splitStr = '-';
    if (timeStr.search("/") > -1)
        splitStr = '/';
    timeStr = timeStr.split(" ");
    var ymdStr = timeStr[0].split(splitStr);
    var hmsStr = timeStr[1].split(':');
    var dateStr = new Date(ymdStr[0], ymdStr[1], ymdStr[2], hmsStr[0], hmsStr[1], hmsStr[2]);
    return dateStr;
}
export class HttpService {
    static query(config, callBack = () => {}) {
        //return;
        config = config || {};
        var params = HttpService.formatParams(config.data);
        var request = new XMLHttpRequest();
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                var status = request.status;
                if (status >= 200 && status < 300) {
                    var res = JSON.parse(request.responseText);
                    if (res) {
                        config.success && config.success(res);
                    }
                } else {
                    return config.fail && config.fail(status);
                }
            }
        };
        request.open('GET', config.url + "?" + params, true);
        request.send(null);
        callBack();
    }

    static save(config) {
        config = config || {};
        var params = HttpService.formatParams(config.data);
        var request = new XMLHttpRequest();
        request.open("POST", config.url, true);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk;");
        request.send(params);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                var status = request.status;
                if (status >= 200 && status < 300) {
                    var res = JSON.parse(request.responseText);
                    if (res) {
                        config.success && config.success(res);
                    }
                } else {
                    config.fail && config.fail(status);
                }
            }
        };
    }

    static formatParams(data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
        }
        //arr.push(("v=" + Math.random()).replace(".", ""));
        return arr.join("&");
    }
}

export let msgTout = null
export const Tips = (msg = '服务异常', duration = 3) => {
    var msgObj = document.querySelector('.tips'),
        msgSpan = msgObj ?
        msgObj.querySelector('span') :
        null;
    if (msgObj == undefined) {
        msgObj = document.createElement('div');
        msgSpan = document.createElement('span');
        msgObj.appendChild(msgSpan);
        msgObj.className = 'tips';
        document.body.appendChild(msgObj);
    }
    msgSpan.innerHTML = msg;
    msgObj.style.bottom = '10rem';
    msgObj.style.display = 'block';
    setTimeout(() => {
        msgObj.style.bottom = '11rem';
        msgObj.style.opacity = '1';
    }, 10)
    clearTimeout(msgTout);
    if (duration == 0)
        return;
    if (duration == -1) {
        msgObj.style.display = 'none';
        return;
    }
    // if (msg.length < 6)
    //     duration = 1
    msgTout = setTimeout(function() {
        msgObj.style.display = 'none';
        msgObj.style.bottom = '10rem';
        msgObj.style.opacity = '0';
    }, duration * 1000);
}
export let countDown = (obj, nowDate, startDate, endDate, callBack) => {
    var difDow = dateFormat(nowDate) - dateFormat(startDate);
    if (difDow > 0)
        startDate = nowDate;
    var difDnd = dateFormat(endDate) - dateFormat(nowDate);
    if (difDow > 0 && difDnd > 0) {
        console.log('ok');
    } else {
        callBack();
        return;
    }
    var intDiff = Math.floor((dateFormat(endDate) - dateFormat(startDate)) / 1000); //秒
    window.setInterval(function() {
        if (intDiff == 0) {
            callBack();
        }
        var day = 0,
            hour = 0,
            minute = 0,
            second = 0; //时间默认值
        if (intDiff > 0) {
            day = Math.floor(intDiff / (24 * 60 * 60));
            hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
            minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
            second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
        }
        if (minute <= 9)
            minute = '0' + minute;
        if (second <= 9)
            second = '0' + second;
        intDiff--;
        var str = day + "天" + hour + "小时" + minute + "分" + second + "秒";
        if (day == 0) {
            str = hour + "时" + minute + "分" + second + "秒";
            if (hour == 0) {
                str = minute + "分" + second + "秒";
                if (minute == "00") {
                    str = second + "秒";
                }
            }
        }
        obj.innerHTML = str;
    }, 1000);
}
export let weixinLogin = (appid = 'wx85577a457cfcd222', redirect_uri = 'http://pay.17find.com/getcode', state = 'pay') => {
    redirect_uri = encodeURIComponent(redirect_uri);
    const urlWxin = 'https://open.weixin.qq.com/connect/oauth2/authorize' +
        '?appid=' + appid + '&redirect_uri=' + redirect_uri + '&response_type=code' + '&scope=snsapi_base' + '&state=' + state + '#wechat_redirect';
    location.href = urlWxin;
}
export let onBridgeReady = (config = {}) => {
    console.log('WeixinJSBridge');
    WeixinJSBridge.invoke('getBrandWCPayRequest', {
        "appId": config.appId, //公众号名称，由商户传入
        "timeStamp": config.timeStamp, //时间戳，自1970年以来的秒数
        "nonceStr": config.nonceStr, //随机串
        "package": config.package,
        "signType": config.signType, //微信签名方式：
        "paySign": config.paySign //微信签名
    }, function(res) {
        if (res.err_msg == "get_brand_wcpay_request:ok") {} // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
    });
}
export let weixinPay = config => {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady(config), false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady(config));
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(config));
        }
    } else {
        onBridgeReady(config);
    }
}

export let imgUpload = (data, callback) => {
    var inputObj = document.getElementById(data.inputId);
    var imgObj = document.getElementById(data.imgId);
    if (inputObj.files && inputObj.files[0]) {
        var fr = new FileReader();
        fr.onload = function() {
            image.src = fr.result;
        };
        var file = inputObj.files[0];
        fr.readAsDataURL(inputObj.files[0]);
        var image = new Image();
        image.onload = function() {
            if (typeof data.scale != 'undefined' && data.scale != '') {
                var scaleW = data.scale.split(':')[0];
                var scaleH = data.scale.split(':')[1];
                if (image.width / scaleW != image.height / scaleH) {
                    inputObj.value = imgObj.src = '';
                    callback(false, '请按图片比例上传（' + data.scale + '）！');
                    return;
                }
            } else {
                var tips = '';
                var valid = true;
                if (typeof data.width != 'undefined' && data.width != '' && image.width != data.width) {
                    tips = '宽度：' + data.width + 'px，';
                    valid = false;
                }
                if (typeof data.height != 'undefined' && data.height != '' && image.height != data.height) {
                    tips += '高度：' + data.height + 'px，';
                    valid = false;
                }
                if (!valid) {
                    inputObj.value = imgObj.src = '';
                    callback(false, '请按图片尺寸上传(' + tips.substr(0, tips.length - 1) + ')');
                    return;
                }
            }
            if (typeof data.size != 'undefined' && data.size != '' && inputObj.files[0].size / 1024 / 1024 > data.size) {
                var sizeLimit = data.size + 'M';
                if (data.size < 1) {
                    sizeLimit = (data.size * 1024).toFixed(0) + 'KB';
                }
                inputObj.value = imgObj.src = '';
                callback(false, '请上传小于 ' + sizeLimit + ' 的图片');
                return;
            }
            var filename = file.name;
            var imgSize = image.src.length;
            var imgUrl = window.URL.createObjectURL(inputObj.files[0]);
            imgObj.src = imgUrl;

            //图片压缩
            imgCompress(imgUrl, imgSize, 800, 0.6, function(baseStr) {
                //base64转二进制流图片
                var text = window.atob(baseStr.split(",")[1]);
                var buffer = new Uint8Array(baseStr.length);
                var pecent = 0,
                    loop = null;
                for (var i = 0; i < text.length; i++) {
                    buffer[i] = text.charCodeAt(i);
                }
                var imgType = baseStr.split(';')[0].split(':')[1];
                var blob = getBlob([buffer], imgType);
                blob.filename = filename;
                callback(true, blob);
                //下载图片查看
                // var link = document.createElement('a');
                // link.href = window.URL.createObjectURL(blob);
                // link.download = filename;
                // link.click();
                // window.URL.revokeObjectURL(link.href);
            });
        };
    } else {
        //IE下，使用滤镜处理，给定宽高
        inputObj.select();
        var imgSrc = document.selection.createRange().text;
        var localImagId = document.getElementById(data.imgIeId);
        //设置初始大小
        var ieWidth = ieHeight = 100;
        if (typeof data.width != 'undefined' && !isNaN(data.width))
            ieWidth = data.width;
        if (typeof data.height != 'undefined' && !isNaN(data.height))
            ieHeight = data.height;
        localImagId.style.width = ieWidth + "px";
        localImagId.style.height = ieHeight + "px";
        //图片异常的捕捉，防止用户修改后缀来伪造图片
        try {
            localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
            localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
        } catch (e) {
            callback('请选择正确的图片格式!');
            return false;
        }
        imgObj.style.display = 'none';
        document.selection.empty();
    }
}

//获取blob对象的兼容性写法
export let getBlob = (buffer, format, filename) => {
    try {
        return new Blob(buffer, {
            type: format,
            filename
        });
    } catch (e) {
        var bb = new(window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
        buffer.forEach(function(buf) {
            bb.append(buf);
        });
        return bb.getBlob(format);
    }
}

//图片压缩
export let imgCompress = (imgUrl, initSize, setWidth = 600, quality = 0.8, callBack) => {
    var setHeight,
        canvas = document.createElement('canvas'),
        context = canvas.getContext('2d'),
        img = new Image();
    img.src = imgUrl;
    img.onload = function() {
        if (setWidth > img.width)
            setWidth = img.width
        setHeight = setWidth / img.width * img.height;
        canvas.width = setWidth;
        canvas.height = setHeight;
        context.drawImage(img, 0, 0, setWidth, setHeight);
        var basestr = canvas.toDataURL('image/jpeg', quality); //后面的小数表示图片的质量
        var newSize = basestr.length;
        console.log('oldSize：' + initSize);
        console.log('newSize：' + newSize);
        console.log('percent：' + (newSize * 100 / initSize).toFixed(2) + '%');
        callBack(basestr);
    }
}

//URL获取关键字内容
export const urlKey = (keyName, newStr = location.href) => {
    var reg = new RegExp(keyName + '=([^&]*)(&|$)', 'i');
    var keyValue = reg.test(newStr) ?
        reg.exec(newStr)[1] :
        '';
    return keyValue.replace(/\s/ig, '');
};
